import { Property } from '@/types/api';
import { CheckOutlined, MinusOutlined, PlusOutlined } from '@ant-design/icons';
import {
  Button,
  Cascader,
  Checkbox,
  Col,
  Collapse,
  Divider,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Row,
  Select,
  Space,
  Typography,
} from 'antd';
import { useEffect, useState } from 'react';
import '../styles/role.scss';
import { Permission, Role } from '@/types/role';
import { useRoleManage, useRoleManageActions, useRoleState } from '@/store/roleManageStore';
import NewRoleFormItem from './NewRoleFormItem';

import roleService from '@/api/services/roleService';
import { Size } from '@/types/common';
import { cvpermission, removeDuplicates } from '@/pages/share-link-manage/utils/link-utils';

import { useDatasetStore } from '@/store/datasetStore';
import { DatasetListItem, DatasetTypeEnum } from '@/common';
import { SvgIcon } from '@/components/icon';
const { SHOW_CHILD } = Cascader;
const { Text } = Typography;

import { findNodeById, findParentIdArray, findParentNameArray } from '@/utils/tree';
import { generateUUID } from '@/utils/common';
import orgService from '@/api/services/orgService';

interface Option {
  key: string;
  value: string | number;
  label: React.ReactNode;
  name: string;
  children?: Option[];
}

const icons: Record<string, React.ReactNode> = {
  dataset: <SvgIcon icon="mdi--folder-zip" size={20} />,
  faq: <SvgIcon icon="mdi--folder-zip" size={20} />,
  folder: <SvgIcon icon="ri--folder-2-fill" size={20} />,
};

const { Panel } = Collapse;
const { TextArea } = Input;

interface Props {
  visible: boolean;
  onCancel: () => void;
  onConfirm?: (item: Role) => void;
  onCancelText?: string;
  onConfirmText?: string;
  initialValues: Role | undefined;
  allDatasets: DatasetListItem[];
  version?: string;
}

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};

const NewRoleModal = ({
  visible,
  onCancel,
  onConfirm,
  initialValues,
  allDatasets,
  version,
}: Props) => {
  const [form] = Form.useForm<Role>();
  const { cdtMetaData, roleManage } = useRoleState();
  const { getRoles, getCdtMetaData, setSelectedRole, getRoleParentArray } = useRoleManageActions();

  const [options, setOptions] = useState<Option[]>([]);
  const [rootDataset, setRootDataset] = useState<{ [key: string]: string }>({});

  const [isFolderEdit, setIsFolderEdit] = useState(false);
  const [folderName, setFolderName] = useState('');
  const { selectedRole } = useRoleManage();
  const { roles } = useRoleState();

  const [apiPermission, setApiPermission] = useState([]);

  useEffect(() => {
    // const array = findParentNameArray(roles, selectedRole.id);
    console.log(roles);
  }, [roles]);

  const getDatasetTags = (permissions: Permission[]) => {
    const datas = cvpermission(allDatasets, permissions);
    // const uniqueDatas = removeDuplicates(datas, permissions, true);
    return datas;
  };

  const generateOptions = (datasets: any[]) => {
    return datasets.map((dataset) => {
      const option: Option = {
        key: dataset._id,
        value: dataset._id,
        label: (
          <div className="inline-block" style={{ verticalAlign: 'middle' }}>
            <div className="flex items-center self-center">
              {icons[dataset.type]} <span className="ml-1">{dataset.name}</span>
            </div>
          </div>
        ),
        name: dataset.name,
        children: dataset.children ? generateOptions(dataset.children) : undefined,
      };
      return option;
    });
  };

  const initModal = () => {
    setRadioValue('none');
    form.setFieldsValue({
      allocation: 'none',
    });
    // loadAllDatasets({
    //   parentId: null,
    // });
  };

  useEffect(() => {
    setRadioValue('none');
    form.setFieldsValue({
      allocation: 'none',
    });
    // loadAllDatasets({
    //   parentId: null,
    // });
  }, []);

  useEffect(() => {
    const result: { [key: string]: string } = {};
    const processDatasets = (datasets: DatasetListItem[]) => {
      datasets.forEach((dataset) => {
        result[dataset._id] = dataset.type;
        if (dataset.children && dataset.children.length > 0) {
          processDatasets(dataset.children);
        }
      });
    };
    processDatasets(allDatasets);
    setRootDataset(result);

    setOptions(generateOptions(allDatasets.filter((item) => item.type != DatasetTypeEnum.api)));
  }, [allDatasets]);

  const filter = (inputValue: string, path: Option[]) => {
    return path.some(
      (option) =>
        option?.name?.toString().includes(inputValue) ||
        (option &&
          option.children &&
          option?.children?.filter((c) => c.name.toString().includes(inputValue)).length > 0),
    );
  };

  const [radioValue, setRadioValue] = useState('none');

  const handleRadioChange = (e) => {
    console.log(e.target.value);
    const selectedValue = e.target.value;
    setRadioValue(selectedValue);
    form.setFieldsValue({
      allocation: selectedValue,
    });
  };

  const validCondition = (role: Role) => {
    try {
      let pass = true;
      if (role.statements) {
        role.statements.forEach((item) => {
          if (!item.condition) {
            pass = false;
            return;
          }
          if (item.condition.length == 0) {
            pass = false;
            return;
          }
        });
      }
      return pass;
    } catch (error) {
      return false;
    }
  };

  type TargetItem = {
    resource_id: string;
    resource_type: string;
    action: string;
  };

  const convertArray = (input: string[][], action: string) => {
    const result: TargetItem[] = [];
    input.forEach((subArray) => {
      subArray.forEach((id: string, index: number) => {
        const item: TargetItem = {
          resource_id: id,
          resource_type: rootDataset[id],
          action: action,
        };
        result.push(item);
      });
    });
    return result;
  };

  const onFinish = async (value: Role) => {
    try {
      console.log(value);
      if (!value?.name?.trim()) {
        message.warning('用户角色名称不能为空！');
        return;
      }

      if (!validCondition(value)) {
        message.warning('请补充限制条件！');
        return;
      }

      // 判断是否需要传递 permissions
      const allocation = form.getFieldValue('allocation');
      const shouldPassPermissions = allocation !== 'none';

      let permissions: TargetItem[] = apiPermission;
      if (value?.adminList) {
        const adminPermissions = convertArray(value.adminList, 'admin');
        permissions = permissions.concat(adminPermissions);
      }
      if (value?.readList) {
        const readPermissions = convertArray(value.readList, 'read');
        permissions = permissions.concat(readPermissions);
      }

      if (initialValues) {
        const roleData = { ...value, id: initialValues.id, name: value?.name?.trim() };
        if (shouldPassPermissions) {
          roleData.permissions = permissions;
        }
        // const role = await roleService.updateRole({ ...value, id: initialValues.id, permissions: permissions });
        // console.log(initialValues);
        // console.log(roleData);
        let role;
        if (version) {
          role = await orgService.updateRole(initialValues.id, roleData);
        } else {
          role = await roleService.updateRole(roleData);
        }
        // console.log(role);

        setSelectedRole(role);
        message.success('更新角色成功！');
      } else {
        // const array = getRoleParentArray();
        // console.log(array)
        // const parent_id = array.length > 0 ? array[0] : (roleManage.selectedRole ? roleManage.selectedRole.id : "")
        const parent_id = roleManage.selectedRole ? roleManage.selectedRole.id : '';
        const roleData = { ...value, parent_id, name: value?.name?.trim() };
        if (shouldPassPermissions) {
          roleData.permissions = permissions;
        }
        const role = await roleService.addRole(roleData);
        // const role = await roleService.addRole({ ...value, parent_id: parent_id, permissions: permissions });
        // setSelectedRole(role);
        message.success('新增角色成功！');
      }
      // await getRoles();
      form.resetFields();
      onCancel();
    } catch (e) {
      console.error(e);
    }
  };

  const getStatementsIndex = () => {
    const statements = form.getFieldValue('statements');
    const index = (statements ? statements.length : 0) + 1;
    return '规则' + index;
  };

  useEffect(() => {
    if (visible) {
      setApiPermission([]);
      getCdtMetaData();
      initModal();
    }
  }, [visible]);

  useEffect(() => {
    const handleDataFetch = async () => {
      if (initialValues) {
        if ((selectedRole?.permissions?.length || 0) > 0) {
          setApiPermission(
            selectedRole?.permissions?.filter((item) => item?.resource_type == DatasetTypeEnum.api),
          );
          const readList = getDatasetTags(
            selectedRole?.permissions?.filter(
              (item) => item?.action == 'read' && item?.resource_type != DatasetTypeEnum.api,
            ),
          );
          const adminList = getDatasetTags(
            selectedRole?.permissions?.filter(
              (item) => item?.action == 'admin' && item?.resource_type != DatasetTypeEnum.api,
            ),
          );
          form.setFieldsValue({ ...initialValues, allocation: 'none', adminList, readList });
        } else {
          setApiPermission([]);
          form.setFieldsValue({ ...initialValues, allocation: 'none' });
        }
      } else {
        setApiPermission([]);
        form.setFieldsValue({ allocation: 'none' });
      }
    };

    setRadioValue('none');
    handleDataFetch();
  }, [initialValues]);

  const handleRoleNameChange = (e) => {
    const name = e.target.value?.trim();
    // const array = findParentNameArray(roles, selectedRole?.id)?.join('-') || ""
    form.setFieldsValue({
      // folder_name: `${array}-${selectedRole?.name}-${e.target.value}`
      folder_name: `${name ? name + '的知识库目录' : ''}`,
    });
    // setFolderName(`${array}-${selectedRole?.name}-${e.target.value}`)
    setFolderName(`${name ? name + '的知识库目录' : ''}`);
  };

  return (
    <Modal
      className="role-new-modal"
      title={
        <div className="justify-left flex" style={{ textAlign: 'left', width: '100%' }}>
          {initialValues ? '更新角色' : '新建角色'}
          {!initialValues && selectedRole?.name && (
            <p
              className="pl-2"
              style={{
                fontSize: '12px',
                fontWeight: 300,
                alignContent: 'end',
                color: 'rgb(142, 147, 164)',
              }}
            >
              创建
              <span style={{ fontWeight: 'bold', color: '#ff7849' }}>{selectedRole?.name}</span>
              的子角色
            </p>
          )}
        </div>
      }
      open={visible}
      onCancel={() => {
        form.resetFields();
        onCancel && onCancel();
      }}
      okText="确定"
      cancelText="取消"
      closable={false}
      width={1000}
      centered
      maskClosable={false}
      footer={<div style={{ textAlign: 'center' }}></div>}
    >
      <div className="mr-10 mt-5 h-full w-full">
        <Form
          layout="vertical"
          form={form}
          name="basic"
          {...formItemLayout}
          autoComplete="on"
          onFinish={onFinish}
        >
          <Form.Item
            label="角色名称"
            name="name"
            wrapperCol={{ span: 24 }}
            rules={[{ required: true, message: '请输入角色名称!' }]}
          >
            <Input
              className="role-input"
              bordered={false}
              placeholder="请输入角色名称"
              disabled={version}
              onChange={handleRoleNameChange}
            />
          </Form.Item>

          <Form.Item
            label="角色说明"
            name="description"
            wrapperCol={{ span: 24 }}
            rules={[{ required: true, message: '请输入角色说明!' }]}
          >
            <TextArea className="role-input" bordered={false} placeholder="请输入角色说明" />
          </Form.Item>

          <Form.List name="statements">
            {(
              fields1,
              { add: addStatement, remove: removeStatement },
              { errors: statementErrors },
            ) => (
              <div className="role-rule-add">
                {fields1.map((field1, index1) => (
                  <Collapse
                    key={`collapse_${field1.key}`}
                    bordered={false}
                    defaultActiveKey={['1']}
                  >
                    <Panel
                      className="mb-2"
                      header={
                        <div className="flex items-center justify-between">
                          {/* <Form.Item
                            noStyle
                            name={[field1.name, 'name']}
                            rules={[{ required: true, message: '请输入规则名称' }]}
                          >
                            <Input
                              disabled
                              className="role-form-input"
                              bordered={false}
                              style={{ width: 200 }}
                              placeholder="规则名称"
                              onClick={(e) => {
                                e.stopPropagation();
                              }}
                            />
                          </Form.Item> */}
                          <div
                            // style={{ flexGrow: 1, textAlign: 'center' }}
                            className="flex"
                          >
                            <div>规则{index1 + 1}</div>
                            <p
                              className="pl-2"
                              style={{
                                fontSize: '12px',
                                fontWeight: 300,
                                alignContent: 'end',
                                color: 'rgb(142, 147, 164)',
                              }}
                            >
                              需满足所有条件，则规则生效
                            </p>
                          </div>
                          <MinusOutlined
                            className="ml-2"
                            onClick={() => removeStatement(field1.name)}
                          />
                        </div>
                      }
                      key="1"
                    >
                      <div key={field1.key} className="rounded-md">
                        <Form.Item
                          // label={index1 === 0 ? '规则' : ''}
                          required={false}
                          {...formItemLayout}
                        >
                          <Form.List name={[field1.name, 'condition']}>
                            {(
                              fields,
                              { add: addCondition, remove: removeCondition },
                              { errors },
                            ) => (
                              <div>
                                {fields.map((field, index) => {
                                  return (
                                    <div key={field.key}>
                                      <NewRoleFormItem
                                        field={field}
                                        index={index}
                                        parentIndex={index1}
                                        form={form}
                                        remove={removeCondition}
                                        cdtMetaData={cdtMetaData}
                                      />
                                    </div>
                                  );
                                })}
                                <Form.Item>
                                  <Button
                                    type="text"
                                    onClick={() =>
                                      addCondition({
                                        key: generateUUID(),
                                      })
                                    }
                                    className="mt-2"
                                    icon={<PlusOutlined />}
                                  >
                                    添加限制条件
                                  </Button>
                                  <Form.ErrorList errors={errors} />
                                </Form.Item>
                              </div>
                            )}
                          </Form.List>
                        </Form.Item>
                      </div>
                    </Panel>
                  </Collapse>
                ))}

                <Form.Item className="flex items-center justify-center">
                  <Button
                    type="text"
                    onClick={() =>
                      addStatement({
                        key: generateUUID(),
                        name: getStatementsIndex(),
                      })
                    }
                    className="mt-2"
                    icon={<PlusOutlined />}
                  >
                    添加规则
                  </Button>
                  <Form.ErrorList errors={statementErrors} />
                </Form.Item>
              </div>
            )}
          </Form.List>

          <Divider />

          {!version && (
            <div className="items-center pb-4">
              <div className="role-modal-title">权限配置</div>

              <div className="p-2">
                <div className="flex items-center">
                  <div className="w-20"></div>
                  <Form.Item label="" name="allocation">
                    <Radio.Group onChange={handleRadioChange} value={radioValue}>
                      <Radio value="none">无操作</Radio>
                      {!initialValues && <Radio value="create">新建目录</Radio>}
                      <Radio value="auth">配置已有知识库</Radio>
                    </Radio.Group>
                  </Form.Item>
                </div>
              </div>

              {(form.getFieldValue('allocation') == 'create' || radioValue == 'create') && (
                <>
                  <Form.Item label="" name="folder_name">
                    <div className="flex items-center p-2">
                      <div className="w-20">目录名称:</div>

                      <>
                        <Text>
                          {/* {folderName + '-' + form.getFieldValue("name")} */}
                          {/* {form.getFieldValue("folder_name") || `${folderName}-${form.getFieldValue("name")}`} */}
                          {/* {folderName} */}
                          {form.getFieldValue('folder_name')}
                        </Text>
                      </>
                    </div>
                  </Form.Item>
                </>
              )}

              {(form.getFieldValue('allocation') == 'auth' || radioValue == 'auth') && (
                <>
                  <div className="flex items-center p-2">
                    <div className="w-20">管理权限:</div>
                    <Form.Item name="adminList" style={{ width: '100%' }}>
                      <Cascader
                        className="share-link-cascader"
                        style={{ width: '100%' }}
                        options={options}
                        placeholder="配置管理权限的知识库"
                        multiple
                        key={'management'}
                        maxTagCount="responsive"
                        showCheckedStrategy={SHOW_CHILD}
                        showSearch={{ filter }}
                        popupClassName="share-link-modal-dropdown"
                      />
                    </Form.Item>
                  </div>

                  <div className="flex items-center p-2">
                    <div className="w-20">问答权限:</div>
                    <Form.Item name="readList" style={{ width: '100%' }}>
                      <Cascader
                        className="share-link-cascader"
                        style={{ width: '100%' }}
                        options={options}
                        placeholder="配置问答权限的知识库"
                        multiple
                        key={'qa'}
                        maxTagCount="responsive"
                        showCheckedStrategy={SHOW_CHILD}
                        showSearch={{ filter }}
                        popupClassName="share-link-modal-dropdown"
                      />
                    </Form.Item>
                  </div>
                </>
              )}
            </div>
          )}

          <Form.Item wrapperCol={{ span: 24 }}>
            <Row>
              <Col span={24} style={{ textAlign: 'right' }}>
                <Button
                  className="w-24"
                  onClick={() => {
                    form.resetFields();
                    onCancel();
                  }}
                >
                  取消
                </Button>
                <Button className="ml-4 w-24" type="primary" htmlType="submit">
                  确定
                </Button>
              </Col>
            </Row>
          </Form.Item>
        </Form>
      </div>
    </Modal>
  );
};

export default NewRoleModal;
